/* eslint-disable no-nested-ternary */
import { useMemo } from 'react';
import round from 'lodash/round';
import { View } from '@tarojs/components';
import style from './index.module.<%= css %>';

interface ICustomTable {
  wrapperStyle?: any;
  columns: any[];
  dataSource: any[];
  rowKeys: string;
}

const CustomTable = (props: ICustomTable) => {
  const { wrapperStyle = {}, columns = [], dataSource = [], rowKeys } = props;

  const calcWidth = useMemo(() => `${round((1 / (columns.length ?? 1)) * 100, 2)}%`, [columns]);

  const renderTableHeader = useMemo(
    () =>
      columns.map((item) => (
        <View
          className={[style.cell, style['header-cell']].join(' ')}
          style={{ width: calcWidth, ...(item.style ?? {}) }}
          key={item.title}
        >
          {item.title}
        </View>
      )),
    [columns]
  );

  const renderBody = useMemo(
    () =>
      dataSource.map((content, index) => (
        <View className={style.row} key={rowKeys ?? index}>
          {columns.map((item) => (
            <View className={style.cell} style={{ width: calcWidth, ...(item.style ?? {}) }} key={item.title}>
              {item.render ? item.render(content[item.key], content, index) : content[item.key]}
            </View>
          ))}
        </View>
      )),
    [dataSource]
  );

  return (
    <View className={style['custom-table-wrapper']} style={wrapperStyle}>
      <View className={style.row}>{renderTableHeader}</View>
      {renderBody}
    </View>
  );
};

export default CustomTable;
